# gptcache配置
# 日志文件
from utils.log import logger
import json
def get_last_content(data,**_):
    prompt = data.get('prompt')    
    r = json.loads(prompt)     
    c = r[-1]['kwargs']['content']  
    print(f'======问题是:{c}========')
    return c



def get_hashed_name(name):
    import hashlib
    hashed = hashlib.sha256(name.encode()).hexdigest()
    return hashed[:8]


# 相似匹配
from gptcache import Cache
from gptcache.embedding import Huggingface
from gptcache.similarity_evaluation import SbertCrossencoderEvaluation
from gptcache.adapter.api import init_similar_cache
def init_gpt_similar_cache(cache_obj:Cache,llm:str):
    name = get_hashed_name(llm)
    import time
    start= time.time()
    embedding = Huggingface()
    logger.info(f'get emmbeding time={time.time()-start}s')
    init_similar_cache(
        embedding=embedding,
        cache_obj=cache_obj,
        pre_func=get_last_content,
        evaluation=SbertCrossencoderEvaluation(),
        data_dir=f'sys_cache/similar_cache_{name}'
    )
 

# 精确匹配
from gptcache.processor.pre import get_prompt
from gptcache.manager.factory import manager_factory
def init_gpt_exact_cache(cache_obj:Cache,llm:str):
    hashed_llm = get_hashed_name(llm)
    cache_obj.init(
        pre_embedding_func=get_last_content,
        data_manager=manager_factory(manager="map", data_dir=f"@sys_cache/exact_cache_{hashed_llm}"),        
    )






